const express = require('express');
const router = express.Router();
const db = require('../config/database');
const { authMiddleware, adminMiddleware, superAdminMiddleware } = require('./auth');
const bcrypt = require('bcrypt'); //  加密数字的模块
// 密码强度验证规则
const PASSWORD_REGEX = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}/;

// 获取所有用户列表
router.get('/users', authMiddleware, adminMiddleware, async (req, res) => {
  try {
    const [users] = await db.pool.execute('SELECT id, username, email, role, created_at FROM users');
    res.json({ code: 0, msg: '成功', data: users });
  } catch (error) {
    console.error(error);
    res.status(500).json({ code: -1, msg: '服务器错误', data: {} });
  }
});

// 更新用户角色（仅超级管理员可操作）
router.put('/users/:id/role', authMiddleware, superAdminMiddleware, async (req, res) => {
  try {
    const { id } = req.params;
    const { role } = req.body;

    if (!['user', 'admin'].includes(role)) {
      return res.status(400).json({ code: -1, msg: '无效的角色类型', data: {} });
    }

    await db.pool.execute('UPDATE users SET role = ? WHERE id = ?', [role, id]);

    // 记录操作日志
    await db.pool.execute(
      'INSERT INTO system_logs (user_id, action, description) VALUES (?, ?, ?)',
      [req.user.id, 'user_update', `更新用户ID ${id} 的角色为 ${role}`]
    );

    res.json({
      code: 0, msg: '更新成功', data: {
        user_role: role
      }
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ code: -1, msg: '服务器错误', data: {} });
  }
});

// 删除用户（仅超级管理员可操作）
router.delete('/users/:id', authMiddleware, superAdminMiddleware, async (req, res) => {
  try {
    const { id } = req.params;

    // 检查是否为超级管理员
    const [user] = await db.pool.execute('SELECT role FROM users WHERE id = ?', [id]);
    if (user[0]?.role === 'super_admin') {
      return res.status(403).json({ code: -1, msg: '不能删除超级管理员账号', data: {} });
    }

    await db.pool.execute('DELETE FROM users WHERE id = ?', [id]);
    // 记录操作日志
    await db.pool.execute(
      'INSERT INTO system_logs (user_id, action, description) VALUES (?, ?, ?)',
      [req.user.id, 'user_delete', `删除用户ID ${id}`]
    );

    res.json({ code: 0, msg: '用户以及关联的所以记录删除成功', data: {} });
  } catch (error) {
    console.error(error);
    if (error.errno === 1451) { // 外键约束错误
      return res.status(400).json({ // 400比401更合适
        code: -1,
        msg: "无法删除：该用户存在关联的借阅记录或评论",
        suggest: "请先清除用户的借阅记录再尝试删除"
      });
    }
    res.status(500).json({ code: -1, msg: '服务器错误', data: {} });
  }
});

// 获取系统日志
router.get('/logs', authMiddleware, adminMiddleware, async (req, res) => {
  try {
    const [logs] = await db.pool.execute(
      `SELECT l.*, u.username 
       FROM system_logs l 
       LEFT JOIN users u ON l.user_id = u.id 
       ORDER BY l.created_at DESC`
    );
    res.json({ code: 0, msg: '获取系统日志成功', data: logs });
  } catch (error) {
    console.error(error);
    res.status(500).json({ code: -1, msg: '服务器错误', data: {} });
  }
});

// 获取管理员列表
router.get("/admins", authMiddleware, superAdminMiddleware, async (req, res) => {
  try {
    const [admins] = await db.pool.execute(
      `
      SELECT users.role, count(*) as total
      FROM users
      WHERE users.role = 'admin' OR users.role = 'super_admin'
      GROUP BY users.role
      `
    )
    res.json({ code: 0, msg: '获取管理员列表成功', data: admins });
  } catch (error) {
    console.error(error);
    res.status(500).json({ code: -1, msg: '服务器错误', data: {} });
  }
})

// 获取系统设置--获取当前用户的信息
router.get("/gettings", authMiddleware, async (req, res) => {
  try {
    const user_id = req.user.id
    const [userInfo] = await db.pool.execute(
      `
      SELECT users.username,users.email,users.password,users.role,users.age,users.major
      FROM users
      WHERE users.id = ?
      `, [user_id]
    )
    // console.log("用户信息：：",userInfo)
    res.json({ code: 0, msg: '获取管理员列表成功', data: userInfo });
  } catch (error) {
    console.error(error);
    res.status(500).json({ code: -1, msg: '服务器错误', data: {} });
  }
})

// 更新系统设置--更新当前用户的信息
router.put("/settings", authMiddleware, async (req, res) => {
  const { now_password, new_password, enter_password } = req.body;
  const userId = req.user.id;

  // 1. 验证输入
  if (!now_password || !new_password || !enter_password) {
    return res.status(400).json({ code: -1, msg: '所有字段都是必填的', data: {} });
  }

  if (new_password !== enter_password) {
    return res.status(400).json({ code: -1, msg: '新密码和确认密码不匹配', data: {} });
  }

  if (new_password === now_password) {
    return res.status(400).json({ code: -1, msg: '新密码不能与当前密码相同', data: {} });
  }

  if (!PASSWORD_REGEX.test(new_password)) {
    return res.status(400).json({
      code: -1,
      msg: '密码必须至少8个字符，包含大小写字母和数字',
      data: {}
    });
  }

  // let connection;
  try {
    // 从连接池获取连接
    let connection = await db.pool.getConnection();

    // 2. 获取用户当前密码哈希
    const [users] = await connection.query(
      'SELECT password FROM users WHERE id = ?',
      [userId]
    );

    if (users.length === 0) {
      return res.status(404).json({ code: -1, msg: '用户不存在', data: {} });
    }

    const user = users[0];

    // 3. 验证当前密码  compare比较
    const isMatch = await bcrypt.compare(now_password, user.password);
    if (!isMatch) {
      return res.status(401).json({ code: -1, msg: '当前密码不正确', data: {} });
    }

    // 4. 更新密码
    const hashedPassword = await bcrypt.hash(new_password, 10);
    await connection.query(
      'UPDATE users SET password = ? WHERE id = ?',
      [hashedPassword, userId]
    );

    // 5. 返回成功响应
    res.json({
      code: 0,
      msg: '密码修改成功',
      data: {}
    });

  } catch (error) {
    console.error('密码修改错误:', error);
    res.status(500).json({ code: -1, msg: '服务器错误', data: {} });
  }
});

// 获取所有系统日志类型
router.get("/logs/types",authMiddleware,async(req,res)=>{
  try{
    const [allType] = await db.pool.execute(
      `
      SELECT COLUMN_TYPE 
      FROM INFORMATION_SCHEMA.COLUMNS 
      WHERE TABLE_NAME = 'system_logs' AND COLUMN_NAME = 'action'
      `
    )
    // 解析 ENUM 值
    const enumStr = allType[0].COLUMN_TYPE; // "enum('艺术','旅游',...)"
    const enumValues = enumStr
      .slice(6, -1)          // 移除 "enum(" 和 ")"
      .split(',')            // 拆分成数组
      .map(v => v.trim().replace(/'/g, '')); // 移除单引号和空格

    console.log(enumValues);
    res.json({
      code: 0,
      msg: "获取所有系统日志类型成功",
      data: enumValues
    })
  } catch (error) {
    console.error('密码修改错误:', error);
    res.status(500).json({ code: -1, msg: '服务器错误', data: {} });
  }
})

module.exports = router;